const fs = require('fs')
const path = require('path')
const pkg = require('../package.json')
const chalk = require('chalk')
const inquirer = require('inquirer')
const { spawnSync } = require('../lib/utils')

const version = pkg.version

console.clear()
console.log('当前版本: ' + chalk.green(version) + '\n')

const publish = async () => {
  const newVersion = 'v' + pkg.version
  const pubState = await spawnSync('npm', ['publish'])
  if (pubState !== 0) {
    console.log(chalk.red('\nnpm bulish failed!'))
    return
  }
  await spawnSync('git', ['add', '.'])
  await spawnSync('git', ['commit', '-m', 'release: ' + newVersion])
  const pushState = await spawnSync('git', ['push', 'origin', 'master'])
  if (pushState !== 0) {
    console.log(chalk.red('\ngit push failed!'))
    return
  }
  await spawnSync('git', ['tag', newVersion])
  await spawnSync('git', ['push', 'origin', newVersion])
  console.log(chalk.green(newVersion + ' publish succeed 👍'))
}

inquirer.prompt([{
  type: 'list',
  name: 'vType',
  message: '请选择版本更新类型:',
  default: '小',
  choices: ['小', '中', '大']
}]).then(({ vType }) => {
  const arr = version.split('.')
  switch (vType) {
    case '小':
      index = 2
      break
    case '中':
      index = 1
      arr[2] = 0
      break
    case '大':
      index = 0
      arr[1] = 0
      arr[2] = 0
      break
    default:
      index = 2
      break
  }
  arr[index] = +arr[index] + 1
  pkg.version = arr.join('.')

  fs.writeFile(path.resolve(__dirname, '../package.json'), JSON.stringify(pkg, null, 2), (err) => {
    if (err) {
      return
    }
    publish()
  })
})